﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace Gollie.Controls
{
	public partial class Download : AuthenticationRequiredAdministratorBaseUserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			string path = Request["path"];
			string file = Request["f"];

			try
			{
				if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(file))
					throw new Exception("Foute url-aanroep");


				if (!Helper.IsAuthorizedForInvoice(path, UserInfo.VendorId))
					throw new Exception("Niet geauthoriseerd");

				using (MemoryStream memStream = new MemoryStream(File.ReadAllBytes(path)))
				{
					string fileName = Path.GetFileName(path);

					Response.ClearContent();
					Response.AddHeader("content-disposition", "attachment; filename=" + file);
					Response.ContentType = System.Web.MimeMapping.GetMimeMapping(fileName);

					memStream.WriteTo(Response.OutputStream);
				}
			}
			catch (Exception ex)
			{
				Response.ClearContent();

				Response.ContentType = System.Web.MimeMapping.GetMimeMapping("a.txt");

				Response.Write("Er is een fout opgetreden: " + ex.Message);

				logger.FatalException("Error downloading " + path, ex);
			}

			Response.End();
		}
	}
}